package com.inspirationandgenius.welcome;

import java.io.ByteArrayOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.lifeofdata.inspirationandgenius.R;

public class Inscription extends Activity implements OnClickListener {

	private ImageView imageView;
	DBAdapter db;
	// Progress Dialog
    private ProgressDialog pDialog;
 
    public String na,lo,pw,em;
    public byte[] userimg;
    
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
    // url to create new product
    private static String url_create_igusers = "http://www.lifeofdata.com/inspirationandgenius/create_igUsers.php";
 
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inscription);
        db = new DBAdapter(this);
        db.open();
        Button add =(Button)findViewById(R.id.inscription);
        add.setOnClickListener(this);
        
        Button chosepic = (Button)findViewById(R.id.choosephoto);
        chosepic.setOnClickListener(this);
    }

	public void onClick(View v) {
		
		switch(v.getId())
		{
			case R.id.choosephoto:
				Intent i = new Intent(
				Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				startActivityForResult(i, 25048899);
				break;
			case R.id.inscription:
				ImageView imag = (ImageView) findViewById(R.id.imageView1);
	            imag.setDrawingCacheEnabled(true);
	            imag.buildDrawingCache();
				Bitmap bitmap = imag.getDrawingCache();
				 
				 ByteArrayOutputStream stream = new ByteArrayOutputStream();
				 bitmap.compress(CompressFormat.PNG, 0, stream);
				 
				 String name = ((EditText)findViewById(R.id.editText1)).getText().toString();
				 String login = ((EditText)findViewById(R.id.editText2)).getText().toString();
				 String pwd = ((EditText)findViewById(R.id.editText3)).getText().toString();
				 String email = ((EditText)findViewById(R.id.editText4)).getText().toString();
				 
				 if(name=="" || login=="" || pwd=="" || email=="")
				 {
					 Toast.makeText(getApplicationContext(), "Required field(s) is missing", Toast.LENGTH_LONG).show();
					 return;
				 }
				 else
				 {
					 na=name;
					 lo=login;
					 
					 MessageDigest md = null;
					try {
						md = MessageDigest.getInstance("MD5");
					} catch (NoSuchAlgorithmException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				        md.update(pwd.getBytes());
				 
				        byte byteData[] = md.digest();
				 
				        //convert the byte to hex format method 1
				        StringBuffer sb = new StringBuffer();
				        for (int i1 = 0; i1 < byteData.length; i1++) {
				         sb.append(Integer.toString((byteData[i1] & 0xff) + 0x100, 16).substring(1));
				        }
				 
				        System.out.println("Digest(in hex format):: " + sb.toString());
				 
				        //convert the byte to hex format method 2
				        StringBuffer hexString = new StringBuffer();
				    	for (int i1=0;i1<byteData.length;i1++) {
				    		String hex=Integer.toHexString(0xff & byteData[i1]);
				   	     	if(hex.length()==1) hexString.append('0');
				   	     	hexString.append(hex);
				    	}
				    	System.out.println("Digest(in hex format):: " + hexString.toString());
					 
					 pw=hexString.toString();
					 em=email;
					 userimg = stream.toByteArray();
					 db.insert_igUsers(na, lo, pw, em, stream.toByteArray());
					new CreateNewigUsers().execute();
				 }
				
	                     Intent i1 = new Intent(getApplicationContext(), ControlTower.class);
	                     startActivity(i1);
	                     finish();
				db.close();
				break;
			default: break;
		}
		
			
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	     super.onActivityResult(requestCode, resultCode, data);
	      
	     if (requestCode == 25048899 && resultCode == RESULT_OK && null != data) {
	            Uri selectedImage = data.getData();
	            String[] filePathColumn = { MediaStore.Images.Media.DATA };
	 
	            Cursor cursor = getContentResolver().query(selectedImage,
	                    filePathColumn, null, null, null);
	            cursor.moveToFirst();
	 
	            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	            String picturePath = cursor.getString(columnIndex);
	            cursor.close();
	             
	            imageView = (ImageView) findViewById(R.id.imageView1);
	            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
	            imageView.setDrawingCacheEnabled(true);
	            imageView.buildDrawingCache();
	            
	         
	        }
	}
	     
	     
	    class CreateNewigUsers extends AsyncTask<String, String, String> {
	    	 
	    
	         protected String doInBackground(String... args) {
	                        // Building Parameters
	             List<NameValuePair> params = new ArrayList<NameValuePair>();
	             params.add(new BasicNameValuePair("name", na));
	             params.add(new BasicNameValuePair("login", lo));
	             params.add(new BasicNameValuePair("pwd", pw));
	             params.add(new BasicNameValuePair("email", em));
	             params.add(new BasicNameValuePair("image", userimg+""));
	  
	             // getting JSON Object
	             // Note that create product url accepts POST method
	             JSONObject json = jParser.makeHttpRequest(url_create_igusers,
	                     "POST", params);
	  
	             // check log cat fro response
	            // Log.d("Create Response", json.toString());
	  
	            
	             return null;
	         }
	  
	        
	  
	     }
   
}
